package org.smart4j.framework.proxy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

/**
 * Created by Wenxin on 2017/3/3.
 */
public class AspectProxy implements Proxy {

    private static final Logger LOGGER = LoggerFactory.getLogger(AspectProxy.class);

    /**
     * 执行代理
     * @param proxyChain
     * @return
     * @throws Throwable
     */
    @Override
    public Object doProxy(ProxyChain proxyChain) throws Throwable {
        Object result = null;

        Class<?> cls = proxyChain.getTargetClass();
        Method method = proxyChain.getTargetMethod();
        Object[] params = proxyChain.getMethodParams();

        begin();
        try {
            if (intercept(cls,method,params)){
                before(cls,method,params);
                result = proxyChain.doProxyChain();
                after(cls,method,params);
            }else
                result = proxyChain.doProxyChain();
        }catch (Exception e){
            LOGGER.error("proxy failure:", e);
            error(cls,method,params,e);
        }finally {
            end();
        }

        return result;
    }

    /**
     *
     */
    public void begin() {
    }

    /**
     * 是否使用增强处理
     * @param cls
     * @param method
     * @param params
     * @return
     * @throws Throwable
     */
    public boolean intercept(Class<?> cls, Method method, Object[] params) throws Throwable {
        return true;
    }

    /**
     * 前置增强
     * @param cls
     * @param method
     * @param params
     * @throws Throwable
     */
    public void before(Class<?> cls, Method method, Object[] params) throws Throwable {
    }

    /**
     * 后置增强
     * @param cls
     * @param method
     * @param params
     * @throws Throwable
     */
    public void after(Class<?> cls, Method method, Object[] params) throws Throwable {
    }

    /**
     * 抛出异常增强
     * @param cls
     * @param method
     * @param params
     * @param e
     */
    public void error(Class<?> cls, Method method, Object[] params, Throwable e) {
    }

    public void end() {
    }




}
